<script setup>
// computed 计算属性
import { ref, computed } from 'vue'
// 引入滑动验证码
import Vcode from 'vue3-puzzle-vcode';
// 引入路由
import { useRouter } from 'vue-router';
// 引入短信验证码组件
import SmsLogin from './ForgetPassword.vue';
// 引入vuex
import { useStore } from 'vuex';
// 引入api
import { UsersLogin } from '../../../AxiosApi/api';
// 
// import{AllPage} from'../HomePage/AllPage.vue'

//实例化vuex                                                                                                                              
const store = useStore();
//接收路由
const router = useRouter();
// 显示短信验证码登录
const sho = ref(false)
// 接收后端返回的数据
const UserItem = ref({})
// 验证码是否显示
const isShow = ref(false)
// for表单数据
const formItem = ref({
    phone: "",
    password: "",
})
// 获取vuex中的isLoginVisible
const isLoginVisible = computed(() => store.getters.isLoginVisible)
// 验证规则
// required：必填，message：提示信息，trigger：触发方式，blur：失去焦点，change：值改变时触发
const rules = ref({
    phone: [
        { required: true, message: "请输入手机号或邮箱", trigger: "blur" },
        { pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$|^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: "请输入正确的手机号或邮箱", trigger: "blur" }
    ],
    password: [
        { required: true, message: "请输入密码", trigger: "blur" },
        { min: 6, max: 15, message: "长度在 6 到 15 之间", trigger: "blur" },
        { pattern: /^(?=.*[a-z])(?=.*[A-Z]).{6,15}$/, message: "密码必须包含大小写字母且长度在 6 到 15 之间", trigger: "blur" }
    ]
})
// 添加表单引用
const formRef = ref(null)
// 提交表单 会根据验证规则来进行判断
// validate 方法是 Element UI 的 <el-form> 组件自带的方法。
// 它用于验证表单中的所有字段，并根据验证规则返回验证结果。
// 控制登录切换
const loginEvents = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            isShow.value = true; // 显示滑动验证码
        } else {
            alert("输入的账户或密码格式不对！请仔细检查！");
        }
    })
}
// 处理滑动验证码成功
const handleCaptchaSuccess = (result) => {
       isShow.value = !isShow.value//隐藏滑动验证码
       // 验证成功后调用后台进行用户信息校验
       checkUser();
};
// 定义接收后端数据并进行比较的方法
const checkUser = async () => {
    const response = await UsersLogin(formItem.value.phone);
    console.log(formItem.value.phone);
    UserItem.value = response.data;
    if (UserItem.value == null) {
        alert("用户不存在，请先注册!");
    } else {
        if (UserItem.value.phone === formItem.value.phone && UserItem.value.password === formItem.value.password) {
            alert("登录成功！即将跳转！");
            // 跳转路由
            router.push('/AllPage')
        } else {
            alert("用户名或密码错误，请重新输入！");
            // 重置表单
            resetForm();
        }
    }
}
// 处理滑动验证码失败
const handleCaptchaFail = (error) => {
    console.error('滑动验证码失败,请重试!:', error);
};
// 切换注册，隐藏登录 
const RegisterEvents = () => {
    // 切换注册页面
    store.dispatch('ShowRegistration', true);
    store.dispatch('ShowLogin', false);
    // 重置表单
    resetForm();
}
// 路由跳转
const Tzrouter = () => {
    store.dispatch("ShowLogin", false)
    sho.value = !sho.value
}
// 重置表单方法
const resetForm = () => {
    formItem.value = {
        phone: "",
        password: "",
        captch: ""
    };
    // resetFields()重置表单字段的值和验证状态
    // ?.：可选链操作符，确保在 formRef.value 为 null 或 undefined 时不会抛出错误。
    formRef.value?.resetFields(); // 清 除表单的验证提示信息
};
</script>
<template>
    <div class="login-div">
        <div class="login-div-2" v-show="isLoginVisible">
            <div class="loginPage">
                <el-form class="login-form" :model="formItem" :rules="rules" ref="formRef">
                    <div class="login-title">登录</div>
                    <el-form-item prop="phone">
                        <el-input v-model="formItem.phone" class="login-input" placeholder="请输入账户:手机号、邮箱" />
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input v-model="formItem.password" class="login-input" placeholder="请输入密码" />
                    </el-form-item>
                    <div class="forget-password">
                        <div class="forget-password-text" @click="Tzrouter">忘记密码?</div>
                    </div>
                    <div class="register-btn-out">
                        <button class="login-btn" type="button" @click="loginEvents">登录</button>
                        <button class="login-btn" type="button" @click="RegisterEvents">注册</button>
                    </div>
                </el-form>
                <Vcode :show="isShow" @success="handleCaptchaSuccess" @fail="handleCaptchaFail" />
            </div>
        </div>
        <!-- 短信验证码登录 组件 -->
        <SmsLogin v-show="sho"></SmsLogin>
    </div>
</template>
<style scoped>
.login-div {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;

}

.login-div-2 {
    width: 100%;
    height: 100%;
    background-color: #e0dddd;
    display: flex;
    align-items: center;
    justify-content: center;
}

.login-form {
    height: 350px;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
    /* border:1px solid  yellow; */
}

.login-title {
    font-size: 40px;
    width: 100%;
    text-align: center;
}

.login-input {
    width: 380px;
    height: 50px;
}

.register-btn-out {
    width: 380px;
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
}

.login-btn {
    width: 150px;
    height: 50px;
    background-color: #008997;
    border-radius: 50px;
    color: white;
    font-size: 20px;
    font-weight: 500;
    border: none;
}

.login-btn:hover {
    color: black;
    background-color: yellow;
    cursor: pointer;
}


.forget-password {
    width: 100%;
    display: flex;
    justify-content: center;
    /* border:1px solid black; */
}

.forget-password-text {
    width: 75px;
    /* border:1px solid black; */
}

.forget-password {
    width: 100%;
    display: flex;
    justify-content: center;
    /* border:1px solid black; */
}

.forget-password-text {
    width: 75px;
    /* border:1px solid black; */
}

.forget-password-text:hover {
    color: white;
    cursor: pointer;
}
</style>